package com.example.demo8;

import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class HeroSelectionUI {
    private List<Hero> heroes = new ArrayList<>();
    private List<Hero> selectedHeroes = new ArrayList<>();
    private ImageView fullImageView;
    private Label descLabel;
    private VBox leftContainer;
    private StackPane detailContainer;
    private StackPane root;
    private boolean twoPlayerMode;
    private Label modeLabel;
    private Consumer<List<Hero>> onHeroSelected;

    public HeroSelectionUI(boolean twoPlayerMode) {
        this.twoPlayerMode = twoPlayerMode;
        initializeUI();
    }

    public void setOnHeroSelected(Consumer<List<Hero>> onHeroSelected) {
        this.onHeroSelected = onHeroSelected;
    }

    public Pane getRoot() {
        return root;
    }

    private void initializeUI() {
        initHeroData();

        // 创建左侧容器（候选英雄区域）
        leftContainer = new VBox();
        leftContainer.setSpacing(15);
        leftContainer.setPadding(new Insets(20));
        leftContainer.setPrefWidth(450);
        leftContainer.setStyle("-fx-background-color: rgba(255, 255, 255, 0.8);");

        // 显示当前模式
        String modeText = twoPlayerMode ? "双人模式：请选择两位英雄" : "单人模式：请选择一位英雄";
        modeLabel = new Label(modeText);
        modeLabel.setFont(Font.font("微软雅黑", FontWeight.BOLD, 20));
        modeLabel.setTextFill(Color.DARKSLATEGRAY);

        Label candidateTitle = new Label("候选英雄");
        candidateTitle.setFont(Font.font("微软雅黑", FontWeight.BOLD, 24));
        candidateTitle.setTextFill(Color.DARKSLATEGRAY);

        GridPane heroGrid = new GridPane();
        heroGrid.setHgap(15);
        heroGrid.setVgap(15);
        heroGrid.setPadding(new Insets(10, 0, 10, 0));

        ColumnConstraints col1 = new ColumnConstraints(200);
        ColumnConstraints col2 = new ColumnConstraints(200);
        heroGrid.getColumnConstraints().addAll(col1, col2);

        RowConstraints row1 = new RowConstraints(200);
        RowConstraints row2 = new RowConstraints(200);
        RowConstraints row3 = new RowConstraints(200);
        heroGrid.getRowConstraints().addAll(row1, row2, row3);

        for (int i = 0; i < heroes.size(); i++) {
            Hero hero = heroes.get(i);
            Pane avatar = createHeroAvatar(hero);
            int row = i / 2;
            int col = i % 2;
            heroGrid.add(avatar, col, row);
        }

        Button selectBtn = new Button("选择英雄");
        selectBtn.setPrefWidth(410);
        selectBtn.setPrefHeight(50);
        selectBtn.setFont(Font.font("微软雅黑", FontWeight.BOLD, 18));
        selectBtn.setStyle(
                "-fx-background-color: #1E90FF; " +
                        "-fx-text-fill: white; " +
                        "-fx-cursor: hand; " +
                        "-fx-border-radius: 5px;"
        );
        selectBtn.setOnAction(e -> showSelectResult());

        Button backBtn = new Button("返回主菜单");
        backBtn.setPrefWidth(410);
        backBtn.setPrefHeight(50);
        backBtn.setFont(Font.font("微软雅黑", FontWeight.BOLD, 18));
        backBtn.setStyle(
                "-fx-background-color: #FF6347; " +
                        "-fx-text-fill: white; " +
                        "-fx-cursor: hand; " +
                        "-fx-border-radius: 5px;"
        );
        backBtn.setOnAction(e -> {
            if (onHeroSelected != null) {
                onHeroSelected.accept(null); // 取消选择，返回主菜单
            }
        });

        leftContainer.getChildren().addAll(modeLabel, candidateTitle, heroGrid, selectBtn, backBtn);

        // 创建右侧英雄详情区域（立绘+描述）
        detailContainer = new StackPane();
        detailContainer.setPrefSize(800, 850);
        detailContainer.setBorder(new Border(new BorderStroke(
                Color.BLACK,
                BorderStrokeStyle.SOLID,
                null,
                new BorderWidths(2)
        )));
        detailContainer.setStyle("-fx-background-color: rgba(255, 255, 255, 0.8);");

        // 初始提示文字
        Label detailLabel = new Label("英雄详情\n（选中英雄后显示信息）");
        detailLabel.setFont(Font.font("微软雅黑", FontWeight.BOLD, 22));
        detailLabel.setTextFill(Color.GRAY);
        detailLabel.setWrapText(true);
        detailLabel.setAlignment(Pos.CENTER);

        // 右侧立绘显示控件
        fullImageView = new ImageView();
        fullImageView.setPreserveRatio(true);
        fullImageView.setFitHeight(600);
        fullImageView.setVisible(false);

        // 英雄描述标签
        descLabel = new Label();
        descLabel.setFont(Font.font("微软雅黑", 16));
        descLabel.setTextFill(Color.BLACK);
        descLabel.setWrapText(true);
        descLabel.setMaxWidth(750);
        descLabel.setPadding(new Insets(10));
        descLabel.setVisible(false);

        // 垂直容器（立绘在上，描述在下）
        VBox detailContent = new VBox(15);
        detailContent.setAlignment(Pos.TOP_CENTER);
        detailContent.getChildren().addAll(fullImageView, descLabel);

        // 将内容容器添加到详情区域
        detailContainer.getChildren().addAll(detailContent, detailLabel);

        // 创建主容器（左右布局）
        HBox mainContainer = new HBox();
        mainContainer.setSpacing(50);
        mainContainer.setPadding(new Insets(20));
        mainContainer.getChildren().addAll(leftContainer, detailContainer);

        // 添加背景图到根容器
        root = new StackPane();
        ImageView backgroundView = createBackgroundView();
        root.getChildren().addAll(backgroundView, mainContainer);
    }

    /**
     * 创建背景图控件
     */
    private ImageView createBackgroundView() {
        ImageView backgroundView = new ImageView();
        try {
            Image backgroundImage = new Image(getClass().getResourceAsStream("/选英雄背景图.jpg"));
            backgroundView.setImage(backgroundImage);
            backgroundView.setFitWidth(1555);
            backgroundView.setFitHeight(973);
            backgroundView.setPreserveRatio(false);
        } catch (Exception e) {
            System.err.println("加载背景图失败！请检查图片路径：/选英雄背景图.jpg");
            System.err.println("错误信息：" + e.getMessage());
            backgroundView.setFitWidth(1555);
            backgroundView.setFitHeight(973);
            backgroundView.setStyle("-fx-background-color: #f0f0f0;");
        }
        return backgroundView;
    }

    private void initHeroData() {
        heroes.add(new Hero("丛雨", "/Hero/Avatar/丛雨.png", "/Hero/Full/丛雨.png",
                "守护穗织镇的「神刀·丛雨丸」付丧神，活了近500年的狐耳巫女。性格温柔端庄，对现代事物充满好奇，战斗时挥舞巨大神刀，拥有封印妖物的力量。"));
        heroes.add(new Hero("小春", "/Hero/Avatar/小春.png", "/Hero/Full/小春.jpg",
                "主角的同班同学，活力满满的元气少女。喜欢摄影，经常来穗织镇采风，性格开朗自来熟，是团队中的「气氛担当」。"));
        heroes.add(new Hero("芦花", "/Hero/Avatar/芦花.jpg", "/Hero/Full/芦花.jpg",
                "穗织镇「青梅馆」温泉旅馆的老板娘，主角的义姐。性格温柔包容，厨艺精湛，表面普通人类，实则与妖物有着不为人知的联系。"));
        heroes.add(new Hero("朝武芳乃", "/Hero/Avatar/芳乃.jpg", "/Hero/Full/朝武芳乃.jpg",
                "穗织镇名家「朝武家」的大小姐，神社的巫女继承人。外表高冷傲娇，实则内心细腻，擅长剑术和神社仪式，肩负守护镇子的重任。"));
        heroes.add(new Hero("茉子", "/Hero/Avatar/茉子.png", "/Hero/Full/茉子.jpg",
                "芳乃的护卫兼青梅竹马，朝武家的分家女儿。性格直率贪吃，力气很大，使用薙刀战斗，对芳乃极其忠诚，梦想是成为「最强女仆」。"));
        heroes.add(new Hero("蕾娜", "/Hero/Avatar/蕾娜.jpg", "/Hero/Full/蕾娜.jpg",
                "来自欧洲的金发留学生，好奇心旺盛的「西洋巫女」。擅长使用符文魔法，性格开朗乐观，经常说出让人意外的日式冷笑话，手持家族传承的魔导书。"));
    }

    private Pane createHeroAvatar(Hero hero) {
        Pane avatar = new Pane();
        avatar.setPrefSize(200, 200);
        avatar.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, null, new BorderWidths(2))));
        avatar.setUserData(hero); // 存储英雄对象

        Image avatarImage;
        try {
            avatarImage = new Image(getClass().getResourceAsStream(hero.getAvatarPath()));
        } catch (Exception e) {
            System.err.println("加载头像失败：" + hero.getAvatarPath() + "，错误：" + e.getMessage());
            avatarImage = new Image(getClass().getResourceAsStream("/Hero/Avatar/default.png"));
        }

        ImageView avatarImageView = new ImageView(avatarImage);
        avatarImageView.setFitWidth(200);
        avatarImageView.setFitHeight(200);
        avatar.getChildren().add(avatarImageView);

        Label nameLabel = new Label(hero.getName());
        nameLabel.setFont(Font.font("微软雅黑", FontWeight.BOLD, 16));
        nameLabel.setTextFill(Color.WHITE);
        nameLabel.setPrefWidth(200);
        nameLabel.setAlignment(Pos.CENTER);
        nameLabel.setStyle("-fx-background-color: rgba(0,0,0,0.5);");
        nameLabel.setLayoutY(170);
        avatar.getChildren().add(nameLabel);

        avatar.setOnMouseEntered(e -> {
            if (!selectedHeroes.contains(hero)) {
                avatar.setBorder(new Border(new BorderStroke(Color.ORANGE, BorderStrokeStyle.SOLID, null, new BorderWidths(2))));
            }
        });
        avatar.setOnMouseExited(e -> {
            if (!selectedHeroes.contains(hero)) {
                avatar.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, null, new BorderWidths(2))));
            }
        });
        avatar.setOnMouseClicked(e -> selectHero(hero, avatar));

        return avatar;
    }

    private void selectHero(Hero hero, Pane avatar) {
        // 显示英雄详情（无论是否选中）
        showHeroDetails(hero);

        // 更新选中状态
        if (twoPlayerMode) {
            handleTwoPlayerSelection(hero, avatar);
        } else {
            handleSinglePlayerSelection(hero, avatar);
        }

        // 更新模式标签
        updateModeLabel();
    }

    private void showHeroDetails(Hero hero) {
        // 加载立绘
        Image fullImage;
        try {
            fullImage = new Image(getClass().getResourceAsStream(hero.getFullImagePath()));
        } catch (Exception ex) {
            System.err.println("加载立绘失败：" + hero.getFullImagePath() + "，错误：" + ex.getMessage());
            fullImage = new Image(getClass().getResourceAsStream("/Hero/Full/default.jpg"));
        }
        fullImageView.setImage(fullImage);
        fullImageView.setVisible(true);

        // 显示描述
        descLabel.setText("【" + hero.getName() + "】\n\n" + hero.getDescription());
        descLabel.setVisible(true);

        // 隐藏初始提示文字
        Label initialDetailLabel = (Label) detailContainer.getChildren().get(1);
        initialDetailLabel.setVisible(false);
    }

    private void handleTwoPlayerSelection(Hero hero, Pane avatar) {
        // 如果英雄已被选中，则取消选择
        if (selectedHeroes.contains(hero)) {
            selectedHeroes.remove(hero);
            avatar.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, null, new BorderWidths(2))));
            return;
        }

        // 如果已选满两个英雄，则替换最后一个
        if (selectedHeroes.size() >= 2) {
            Hero lastHero = selectedHeroes.remove(selectedHeroes.size() - 1);
            resetAvatarBorder(lastHero);
        }

        // 添加新英雄
        selectedHeroes.add(hero);
        avatar.setBorder(new Border(new BorderStroke(Color.ORANGE, BorderStrokeStyle.SOLID, null, new BorderWidths(3))));
    }

    private void handleSinglePlayerSelection(Hero hero, Pane avatar) {
        // 如果英雄已被选中，则取消选择
        if (selectedHeroes.contains(hero)) {
            selectedHeroes.clear();
            resetAllAvatarBorders();
            return;
        }

        // 取消之前选中的英雄
        selectedHeroes.clear();
        resetAllAvatarBorders();

        // 添加新英雄
        selectedHeroes.add(hero);
        avatar.setBorder(new Border(new BorderStroke(Color.ORANGE, BorderStrokeStyle.SOLID, null, new BorderWidths(3))));
    }

    private void resetAvatarBorder(Hero hero) {
        GridPane heroGrid = (GridPane) leftContainer.getChildren().get(2); // 索引2是GridPane
        for (javafx.scene.Node node : heroGrid.getChildren()) {
            if (node instanceof Pane && node.getUserData() == hero) {
                ((Pane) node).setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, null, new BorderWidths(2))));
            }
        }
    }

    private void resetAllAvatarBorders() {
        GridPane heroGrid = (GridPane) leftContainer.getChildren().get(2); // 索引2是GridPane
        for (javafx.scene.Node node : heroGrid.getChildren()) {
            if (node instanceof Pane) {
                ((Pane) node).setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, null, new BorderWidths(2))));
            }
        }
    }

    private void updateModeLabel() {
        if (twoPlayerMode) {
            modeLabel.setText("双人模式：已选择 " + selectedHeroes.size() + "/2 位英雄");
        } else {
            modeLabel.setText("单人模式：" + (selectedHeroes.isEmpty() ? "请选择英雄" : "已选择 " + selectedHeroes.get(0).getName()));
        }
    }

    private void showSelectResult() {
        if (selectedHeroes.isEmpty()) {
            new Alert(Alert.AlertType.WARNING, "请先选择一个英雄！").showAndWait();
            return;
        }

        if (twoPlayerMode && selectedHeroes.size() < 2) {
            new Alert(Alert.AlertType.WARNING, "请选择两位英雄！").showAndWait();
            return;
        }

        // 调用回调函数，传递选中的英雄
        if (onHeroSelected != null) {
            onHeroSelected.accept(selectedHeroes);
        }
    }
}